<?php
/**
 * 分页类
 * 
 * @version $Id: Pagination.php 174 2011-05-18 02:38:13Z linsir123 $
 */
class comPagination
{
	///
	public $url;
	public $pageId;
	public $pageCount;
	public $pageShow;
	
	/**
	 * 构造函数
	 */
	public function __construct($url, $pageCount, $pageShow = 10, $pageTag = 'p')
	{
		$pageId = isset($_GET[$pageTag]) ? intval($_GET[$pageTag]) : 1;
		if ($pageId < 1) 
			$pageId = 1;
		elseif ($pageId > $pageCount) 
			$pageId = $pageCount;
		
		///
		$this->url = $url.'/'.$pageTag.'/%d';
		$this->pageId = $pageId;
		$this->pageCount = $pageCount;
		$this->pageShow = $pageShow;
	}
	
	/**
	 * 以分页，显示分页内容
	 */
	public function display()
	{
		if ($this->pageCount < 1) 
			return false;
			
		///
		$pageShow2 = $this->pageShow - 1;
		$halfStart = floor($pageShow2 / 2);
		$halfEnd = ceil($pageShow2 / 2);
		$startPage = $this->pageId - $halfStart;
		$endPage = $this->pageId + $halfEnd;
		
		///
		if ($startPage <= 0) 
			$startPage = 1;
			
		if (($endPage - $startPage) != $pageShow2) 
			$endPage = $startPage + $pageShow2;
			
		if ($endPage > $this->pageCount) {
			$startPage = $this->pageCount - $pageShow2;
			$endPage = $this->pageCount;
		}
		
		///
		$nav = '';
		$hrefFormat = "<a href=\"{$this->url}\" p=\"%d\">%s</a>\r\n";
		if ($this->pageId > 1) {
			$nav .= sprintf($hrefFormat, 1, 1, I18n::__('|&lt; first'));
			$nav .= sprintf($hrefFormat, $this->pageId - 1, $this->pageId - 1, I18n::__('&lt; pre'));
		}
		if ($startPage >= 2 && $this->pageShow < $this->pageCount) 
			$nav .= "<span>...</span>\r\n";
			
		///
		for ($i = $startPage; $i <= $endPage; $i++) {
			if ($i == $this->pageId) 
				$nav .= "<span class=\"current\">$i</span>\r\n";
			else
				$nav .= sprintf($hrefFormat, $i, $i, $i);
		}
		
		///
		if ($endPage < $this->pageCount) 
			$nav .= "<span>...</span>\r\n";
			
		if ($this->pageId < $this->pageCount) {
			$nav .= sprintf($hrefFormat, $this->pageId + 1, $this->pageId + 1, I18n::__('next &gt;'));
			$nav .= sprintf($hrefFormat, $this->pageCount, $this->pageCount, I18n::__('last &gt;|'));
		}
		
		return "<div id=\"page_nav\">\r\n{$nav}</div>";
	}
}
